/**
 * 校园二手交易平台 - 商品模拟数据
 * 为校园二手交易平台提供高质量、多样化的商品模拟数据
 * 支持搜索、筛选、排序等完整功能测试
 */

import { defineMock } from "umi";
import {
  Product,
  ProductCategory,
  ProductCondition,
  ProductStatus,
  TransactionMethod,
  ProductListResponse,
  ProductStats,
  ProductOperationResult,
  ProductSearchSuggestion,
} from '../types/product';

// 校园信息配置
const SCHOOLS = [
  { name: '清华大学', campuses: ['清华园校区', '深圳研究生院', '新雅书院'] },
  { name: '北京大学', campuses: ['燕园校区', '医学部校区', '昌平校区'] },
  { name: '复旦大学', campuses: ['邯郸校区', '枫林校区', '江湾校区', '张江校区'] },
  { name: '上海交通大学', campuses: ['闵行校区', '徐汇校区', '七宝校区'] },
  { name: '浙江大学', campuses: ['紫金港校区', '玉泉校区', '西溪校区', '华家池校区'] },
  { name: '南京大学', campuses: ['仙林校区', '鼓楼校区', '浦口校区'] },
  { name: '武汉大学', campuses: ['珞珈山校区', '信息学部', '医学部'] },
  { name: '中山大学', campuses: ['广州校区', '珠海校区', '深圳校区'] },
];

// 商品标题模板（按类别）
const PRODUCT_TITLES = {
  [ProductCategory.TEXTBOOKS]: [
    '高等数学（第七版）上下册', '英语四级词汇宝典', '计算机程序设计教程',
    '微观经济学原理', '大学物理实验指导', '线性代数及其应用',
    'C++程序设计（谭浩强）', '数据结构与算法分析', '操作系统概念',
    '计算机网络（谢希仁）', '数据库系统概论', '软件工程导论',
    '概率论与数理统计', '离散数学教程', '编译原理与技术',
    '人工智能导论', '机器学习基础', '数字电路与逻辑设计'
  ],
  [ProductCategory.ELECTRONICS]: [
    'MacBook Pro 13寸 2020款', 'ThinkPad X1 Carbon 2021', 'iPad Air 4代',
    '华为MateBook 14', '小米RedmiBook Pro', '戴尔XPS 13',
    'iPhone 13 Pro Max', '华为P50 Pro', '小米12 Ultra',
    'AirPods Pro 2代', '索尼WH-1000XM4', 'Bose QC35 II',
    '佳能EOS R6微单', '尼康Z6 II', '富士X-T4',
    '任天堂Switch OLED', 'PS5游戏主机', 'Xbox Series X'
  ],
  [ProductCategory.CLOTHING]: [
    '优衣库保暖羽绒服', 'Nike Air Force 1运动鞋', 'Adidas三叶草卫衣',
    '李宁篮球鞋实战款', '匡威经典帆布鞋', 'Vans Old Skool板鞋',
    'ZARA秋冬款大衣', 'H&M针织毛衣', 'Gap连帽卫衣',
    '北面冲锋衣防水', '哥伦比亚保暖夹克', '探路者登山鞋'
  ],
  [ProductCategory.DAILY_GOODS]: [
    '象印保温杯480ml', '美的智能台灯', '无印良品收纳箱',
    '飞利浦电动牙刷', '小米智能音箱', '九阳电热水壶',
    '苏泊尔电饭煲', '海尔迷你冰箱', '格力电风扇',
    '罗技无线鼠标', '宜家书桌台灯', '乐扣乐扣保鲜盒'
  ],
  [ProductCategory.SPORTS]: [
    '斯伯丁篮球7号', '尤尼克斯羽毛球拍', '李宁瑜伽垫',
    '阿迪达斯足球', '威尔逊网球拍', '耐克跑步鞋',
    '迪卡侬登山杖', 'Keep健身器材', '匹克运动护具'
  ],
  [ProductCategory.STATIONERY]: [
    '无印良品笔记本套装', '百乐P500中性笔', '三菱UMN-105',
    '卡西欧科学计算器', '国誉活页本', '斑马JJ15',
    '施耐德钢笔', '得力文具套装', '晨光考试专用笔'
  ],
  [ProductCategory.DORMITORY]: [
    '记忆棉床垫1.2米', '可折叠书桌', '多层收纳衣柜',
    '宿舍专用小冰箱', '迷你洗衣机', '电热毯单人',
    '床上用品四件套', '蚊帐支架套装', '窗帘遮光布'
  ],
  [ProductCategory.OTHER]: [
    '手工艺品DIY材料', '闲置小礼品', '收藏邮票册',
    '乐器吉他民谣', '摄影器材三脚架', '盆栽绿植多肉',
    '书籍小说文集', '动漫周边手办', '旅行背包登山'
  ]
};

// 商品描述模板
const PRODUCT_DESCRIPTIONS = {
  [ProductCategory.TEXTBOOKS]: [
    '教材保持完好，无涂写痕迹，适合新生使用。附赠课后习题答案。',
    '专业课教材，内容详实，重点标注清晰，含历年考试重点。',
    '经典教材版本，学长学姐推荐，备考必备书籍。',
    '教材配套习题册完整，学习笔记整洁，帮助理解知识点。'
  ],
  [ProductCategory.ELECTRONICS]: [
    '电子产品保养良好，功能正常，原装配件齐全，支持验机。',
    '个人自用设备，无维修记录，电池健康度良好，性能稳定。',
    '国行正品，包装配件完整，支持面交验货，价格可小刀。',
    '升级换代闲置，外观轻微使用痕迹，功能一切正常。'
  ],
  [ProductCategory.CLOTHING]: [
    '衣物清洗干净，尺码标准，适合校园日常穿着，舒适耐穿。',
    '品牌正品，款式经典，保养得当，无明显磨损痕迹。',
    '季节性闲置，穿着次数不多，保持干净整洁状态。',
    '校园风格服饰，适合学生群体，价格实惠质量好。'
  ]
};

// 默认商品描述（其他类别使用）
const DEFAULT_DESCRIPTION = '校园闲置物品，保持良好状态，价格实惠，支持面交验货。';

// 用户信息（模拟不同发布者）
const USERS = [
  { id: 'user_001', username: '学霸小明', avatar: 'https://i.pravatar.cc/150?img=1', verified: true },
  { id: 'user_002', username: '技术宅小李', avatar: 'https://i.pravatar.cc/150?img=2', verified: true },
  { id: 'user_003', username: '文艺青年小王', avatar: 'https://i.pravatar.cc/150?img=3', verified: true },
  { id: 'user_004', username: '运动达人小张', avatar: 'https://i.pravatar.cc/150?img=4', verified: true },
  { id: 'user_005', username: '生活家小刘', avatar: 'https://i.pravatar.cc/150?img=5', verified: false },
  { id: 'user_006', username: '游戏爱好者小陈', avatar: 'https://i.pravatar.cc/150?img=6', verified: true },
  { id: 'user_007', username: '摄影爱好者小赵', avatar: 'https://i.pravatar.cc/150?img=7', verified: false },
  { id: 'user_008', username: '音乐才子小钱', avatar: 'https://i.pravatar.cc/150?img=8', verified: true }
];

// 生成随机商品数据
function generateMockProducts(count: number = 150): Product[] {
  const products: Product[] = [];
  const categories = Object.values(ProductCategory);
  const conditions = Object.values(ProductCondition);
  const statuses = [ProductStatus.ACTIVE, ProductStatus.ACTIVE, ProductStatus.ACTIVE, ProductStatus.SOLD, ProductStatus.INACTIVE];
  
  // 各类别商品数量分布（更符合校园实际）
  const categoryDistribution = {
    [ProductCategory.TEXTBOOKS]: 0.25,    // 25% 教材
    [ProductCategory.ELECTRONICS]: 0.20,  // 20% 电子产品
    [ProductCategory.CLOTHING]: 0.15,     // 15% 服饰
    [ProductCategory.DAILY_GOODS]: 0.12,  // 12% 生活用品
    [ProductCategory.SPORTS]: 0.08,       // 8% 体育用品
    [ProductCategory.STATIONERY]: 0.07,   // 7% 学习用品
    [ProductCategory.DORMITORY]: 0.08,    // 8% 宿舍用品
    [ProductCategory.OTHER]: 0.05         // 5% 其他
  };

  // 价格区间配置（按类别）
  const priceRanges = {
    [ProductCategory.TEXTBOOKS]: { min: 15, max: 120 },
    [ProductCategory.ELECTRONICS]: { min: 200, max: 5000 },
    [ProductCategory.CLOTHING]: { min: 30, max: 300 },
    [ProductCategory.DAILY_GOODS]: { min: 20, max: 200 },
    [ProductCategory.SPORTS]: { min: 40, max: 400 },
    [ProductCategory.STATIONERY]: { min: 10, max: 100 },
    [ProductCategory.DORMITORY]: { min: 50, max: 300 },
    [ProductCategory.OTHER]: { min: 20, max: 200 }
  };

  let productId = 1;
  
  // 按类别分布生成商品
  Object.entries(categoryDistribution).forEach(([category, ratio]) => {
    const categoryCount = Math.floor(count * ratio);
    
    for (let i = 0; i < categoryCount; i++) {
      const school = SCHOOLS[Math.floor(Math.random() * SCHOOLS.length)];
      const campus = school.campuses[Math.floor(Math.random() * school.campuses.length)];
      const user = USERS[Math.floor(Math.random() * USERS.length)];
      
      const priceRange = priceRanges[category as ProductCategory];
      const price = Math.floor(Math.random() * (priceRange.max - priceRange.min)) + priceRange.min;
      const originalPrice = Math.floor(price * (1 + Math.random() * 0.5)); // 原价比现价高0-50%
      
      const condition = conditions[Math.floor(Math.random() * conditions.length)];
      const status = statuses[Math.floor(Math.random() * statuses.length)];
      
      const titles = PRODUCT_TITLES[category as ProductCategory];
      const title = titles[Math.floor(Math.random() * titles.length)];
      
      const descriptions = PRODUCT_DESCRIPTIONS[category as ProductCategory] || [DEFAULT_DESCRIPTION];
      const description = descriptions[Math.floor(Math.random() * descriptions.length)];
      
      // 根据新旧程度调整价格
      let adjustedPrice = price;
      switch (condition) {
        case ProductCondition.NEW:
          adjustedPrice = price * 0.9; // 全新打9折
          break;
        case ProductCondition.LIKE_NEW:
          adjustedPrice = price * 0.8; // 九成新打8折
          break;
        case ProductCondition.VERY_GOOD:
          adjustedPrice = price * 0.7; // 八成新打7折
          break;
        case ProductCondition.GOOD:
          adjustedPrice = price * 0.6; // 七成新打6折
          break;
        case ProductCondition.FAIR:
          adjustedPrice = price * 0.5; // 六成新打5折
          break;
        case ProductCondition.POOR:
          adjustedPrice = price * 0.3; // 五成新及以下打3折
          break;
      }
      
      const product: Product = {
        id: `product_${productId++}`,
        title: `${title} - ${school.name}`,
        description: description,
        price: Math.round(adjustedPrice),
        originalPrice: Math.round(originalPrice),
        category: category as ProductCategory,
        condition,
        transactionMethod: Math.random() > 0.3 ? TransactionMethod.FACE_TO_FACE : 
                         Math.random() > 0.5 ? TransactionMethod.MAIL : TransactionMethod.BOTH,
        images: generateProductImages(productId),
        location: {
          school: school.name,
          campus,
          address: `${campus}学生宿舍区`,
          longitude: 116.3 + Math.random() * 0.5,
          latitude: 39.9 + Math.random() * 0.3
        },
        publisher: {
          userId: user.id,
          username: user.username,
          avatar: user.avatar,
          isStudentVerified: user.verified,
          school: school.name,
          contactInfo: {
            phone: Math.random() > 0.7 ? `138${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}` : undefined,
            wechat: Math.random() > 0.5 ? `wx_${user.username}` : undefined
          }
        },
        publishedAt: new Date(Date.now() - Math.floor(Math.random() * 90 * 24 * 60 * 60 * 1000)), // 90天内
        updatedAt: new Date(),
        status,
        viewCount: Math.floor(Math.random() * 500),
        favoriteCount: Math.floor(Math.random() * 50),
        inquiryCount: Math.floor(Math.random() * 20),
        tags: generateProductTags(category as ProductCategory, condition),
        isNegotiable: Math.random() > 0.4,
        isFreeShipping: Math.random() > 0.7,
        shippingFee: Math.random() > 0.7 ? Math.floor(Math.random() * 15) + 5 : undefined,
        stock: status === ProductStatus.SOLD ? 0 : Math.floor(Math.random() * 3) + 1,
        isReturnable: Math.random() > 0.8,
        returnPolicy: Math.random() > 0.8 ? '7天内无理由退换，需保持商品完好' : undefined
      };
      
      products.push(product);
    }
  });
  
  return products.slice(0, count); // 确保总数不超过count
}

// 生成商品图片
function generateProductImages(productId: number): Product['images'] {
  const imageCount = Math.floor(Math.random() * 3) + 1; // 1-3张图片
  const images = [];
  
  for (let i = 1; i <= imageCount; i++) {
    images.push({
      id: `img_${productId}_${i}`,
      url: `https://picsum.photos/600/400?random=${productId * 10 + i}`,
      thumbnailUrl: `https://picsum.photos/300/200?random=${productId * 10 + i}`,
      isCover: i === 1,
      description: `商品图片 ${i}`,
      uploadedAt: new Date()
    });
  }
  
  return images;
}

// 生成商品标签
function generateProductTags(category: ProductCategory, condition: ProductCondition): string[] {
  const baseTags = ['校园', '二手', '学生', '实惠'];
  const categoryTags = {
    [ProductCategory.TEXTBOOKS]: ['教材', '学习', '考试', '专业课'],
    [ProductCategory.ELECTRONICS]: ['数码', '科技', '智能', '品牌'],
    [ProductCategory.CLOTHING]: ['时尚', '潮流', '品牌', '穿搭'],
    [ProductCategory.DAILY_GOODS]: ['生活', '实用', '家居', '日常'],
    [ProductCategory.SPORTS]: ['运动', '健身', '健康', '户外'],
    [ProductCategory.STATIONERY]: ['学习', '文具', '办公', '书写'],
    [ProductCategory.DORMITORY]: ['宿舍', '住宿', '收纳', '布置'],
    [ProductCategory.OTHER]: ['闲置', '创意', '收藏', '手工']
  };
  
  const conditionTags = {
    [ProductCondition.NEW]: ['全新', '未使用', '包装完好'],
    [ProductCondition.LIKE_NEW]: ['九九新', '几乎全新', '轻微使用'],
    [ProductCondition.VERY_GOOD]: ['八五新', '保养良好', '功能完好'],
    [ProductCondition.GOOD]: ['七成新', '正常使用', '性价比高'],
    [ProductCondition.FAIR]: ['六成新', '使用痕迹', '实惠'],
    [ProductCondition.POOR]: ['五成新', '老旧', '超值']
  };
  
  return [...baseTags, ...categoryTags[category], ...conditionTags[condition]].slice(0, 8);
}

// 全局商品数据缓存
let mockProducts: Product[] = generateMockProducts(150);

// 数据处理函数
function filterAndSortProducts(
  products: Product[], 
  params: any
): ProductListResponse {
  let filteredProducts = [...products];
  
  // 关键字搜索
  if (params.keyword) {
    const keyword = params.keyword.toLowerCase();
    filteredProducts = filteredProducts.filter(product => 
      product.title.toLowerCase().includes(keyword) ||
      product.description.toLowerCase().includes(keyword) ||
      product.tags?.some(tag => tag.toLowerCase().includes(keyword))
    );
  }
  
  // 类别筛选
  if (params.category) {
    filteredProducts = filteredProducts.filter(product => product.category === params.category);
  }
  
  // 新旧程度筛选
  if (params.condition) {
    filteredProducts = filteredProducts.filter(product => product.condition === params.condition);
  }
  
  // 学校筛选
  if (params.school) {
    filteredProducts = filteredProducts.filter(product => product.location.school === params.school);
  }
  
  // 价格范围筛选
  if (params.priceRange) {
    const { min, max } = params.priceRange;
    if (min !== undefined) {
      filteredProducts = filteredProducts.filter(product => product.price >= min);
    }
    if (max !== undefined) {
      filteredProducts = filteredProducts.filter(product => product.price <= max);
    }
  }
  
  // 只显示上架商品
  if (params.onlyActive) {
    filteredProducts = filteredProducts.filter(product => product.status === ProductStatus.ACTIVE);
  }
  
  // 排序
  if (params.sortBy) {
    filteredProducts.sort((a, b) => {
      const order = params.sortOrder === 'asc' ? 1 : -1;
      switch (params.sortBy) {
        case 'price':
          return (a.price - b.price) * order;
        case 'publishedAt':
          return (a.publishedAt.getTime() - b.publishedAt.getTime()) * order;
        case 'viewCount':
          return (a.viewCount - b.viewCount) * order;
        case 'favoriteCount':
          return (a.favoriteCount - b.favoriteCount) * order;
        default:
          return 0;
      }
    });
  }
  
  // 分页
  const page = params.page || 1;
  const pageSize = params.pageSize || 20;
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedProducts = filteredProducts.slice(startIndex, endIndex);
  
  return {
    products: paginatedProducts,
    total: filteredProducts.length,
    currentPage: page,
    totalPages: Math.ceil(filteredProducts.length / pageSize),
    pageSize
  };
}

export default defineMock({
  // 获取商品列表
  'GET /api/products/list': (req, res) => {
    const params = req.query;
    const result = filterAndSortProducts(mockProducts, params);
    
    // 模拟网络延迟
    setTimeout(() => {
      res.status(200).json(result);
    }, 200 + Math.random() * 300);
  },
  
  // 获取商品详情
  'GET /api/products/detail/:id': (req, res) => {
    const { id } = req.params;
    const product = mockProducts.find(p => p.id === id);
    
    setTimeout(() => {
      if (product) {
        res.status(200).json(product);
      } else {
        res.status(404).json({
          success: false,
          message: '商品不存在',
          error: 'PRODUCT_NOT_FOUND'
        });
      }
    }, 150 + Math.random() * 200);
  },
  
  // 创建商品
  'POST /api/products/create': (req, res) => {
    const productData = req.body;
    const newProduct: Product = {
      id: `product_${Date.now()}`,
      ...productData,
      images: productData.images || [],
      location: {
        school: productData.school,
        campus: productData.campus,
        address: productData.address,
      },
      publisher: {
        userId: 'current_user',
        username: '当前用户',
        isStudentVerified: true,
        school: productData.school,
      },
      publishedAt: new Date(),
      updatedAt: new Date(),
      status: ProductStatus.ACTIVE,
      viewCount: 0,
      favoriteCount: 0,
      inquiryCount: 0,
      isNegotiable: productData.isNegotiable || false,
      stock: productData.stock || 1,
      isReturnable: productData.isReturnable || false,
    };
    
    mockProducts.unshift(newProduct);
    
    setTimeout(() => {
      res.status(200).json({
        success: true,
        message: '商品发布成功',
        product: newProduct
      });
    }, 300);
  },
  
  // 更新商品
  'PUT /api/products/update/:id': (req, res) => {
    const { id } = req.params;
    const updateData = req.body;
    const productIndex = mockProducts.findIndex(p => p.id === id);
    
    setTimeout(() => {
      if (productIndex === -1) {
        res.status(404).json({
          success: false,
          message: '商品不存在',
          error: 'PRODUCT_NOT_FOUND'
        });
        return;
      }
      
      mockProducts[productIndex] = {
        ...mockProducts[productIndex],
        ...updateData,
        updatedAt: new Date()
      };
      
      res.status(200).json({
        success: true,
        message: '商品更新成功',
        product: mockProducts[productIndex]
      });
    }, 250);
  },
  
  // 删除商品
  'DELETE /api/products/delete/:id': (req, res) => {
    const { id } = req.params;
    
    setTimeout(() => {
      mockProducts = mockProducts.filter(p => p.id !== id);
      
      res.status(200).json({
        success: true,
        message: '商品删除成功'
      });
    }, 200);
  },
  
  // 商品状态切换
  'PATCH /api/products/status/:id': (req, res) => {
    const { id } = req.params;
    const { status } = req.body;
    const productIndex = mockProducts.findIndex(p => p.id === id);
    
    setTimeout(() => {
      if (productIndex === -1) {
        res.status(404).json({
          success: false,
          message: '商品不存在',
          error: 'PRODUCT_NOT_FOUND'
        });
        return;
      }
      
      mockProducts[productIndex].status = status;
      mockProducts[productIndex].updatedAt = new Date();
      
      res.status(200).json({
        success: true,
        message: `商品${status === 'active' ? '上架' : '下架'}成功`,
        product: mockProducts[productIndex]
      });
    }, 180);
  },
  
  // 搜索商品
  'GET /api/products/search': (req, res) => {
    const { keyword, ...params } = req.query;
    const searchParams = { ...params, keyword };
    const result = filterAndSortProducts(mockProducts, searchParams);
    
    setTimeout(() => {
      res.status(200).json(result);
    }, 250 + Math.random() * 200);
  },
  
  // 获取搜索建议
  'GET /api/products/search/suggestions': (req, res) => {
    const { keyword } = req.query;
    
    const suggestions: ProductSearchSuggestion[] = [
      { type: 'keyword', value: '笔记本电脑', count: 23 },
      { type: 'keyword', value: '教材', count: 45 },
      { type: 'keyword', value: 'iPhone', count: 12 },
      { type: 'category', value: '电子产品', count: 67 },
      { type: 'category', value: '教材书籍', count: 89 },
      { type: 'tag', value: '校园', count: 156 },
      { type: 'tag', value: '实惠', count: 134 },
    ];
    
    const filteredSuggestions = keyword ? 
      suggestions.filter(s => s.value.toLowerCase().includes(keyword.toLowerCase())) :
      suggestions.slice(0, 5);
    
    setTimeout(() => {
      res.status(200).json(filteredSuggestions);
    }, 150);
  },
  
  // 获取商品统计
  'GET /api/products/stats': (req, res) => {
    const stats: ProductStats = {
      totalProducts: mockProducts.length,
      activeProducts: mockProducts.filter(p => p.status === 'active').length,
      soldProducts: mockProducts.filter(p => p.status === 'sold').length,
      todayNewProducts: mockProducts.filter(p => 
        new Date(p.publishedAt).toDateString() === new Date().toDateString()
      ).length,
      categoryStats: {
        [ProductCategory.TEXTBOOKS]: mockProducts.filter(p => p.category === ProductCategory.TEXTBOOKS).length,
        [ProductCategory.ELECTRONICS]: mockProducts.filter(p => p.category === ProductCategory.ELECTRONICS).length,
        [ProductCategory.CLOTHING]: mockProducts.filter(p => p.category === ProductCategory.CLOTHING).length,
        [ProductCategory.DAILY_GOODS]: mockProducts.filter(p => p.category === ProductCategory.DAILY_GOODS).length,
        [ProductCategory.SPORTS]: mockProducts.filter(p => p.category === ProductCategory.SPORTS).length,
        [ProductCategory.STATIONERY]: mockProducts.filter(p => p.category === ProductCategory.STATIONERY).length,
        [ProductCategory.DORMITORY]: mockProducts.filter(p => p.category === ProductCategory.DORMITORY).length,
        [ProductCategory.OTHER]: mockProducts.filter(p => p.category === ProductCategory.OTHER).length,
      }
    };
    
    setTimeout(() => {
      res.status(200).json(stats);
    }, 300);
  },
  
  // 获取我的商品
  'GET /api/products/my-products': (req, res) => {
    const params = { ...req.query, onlyActive: false };
    const myProducts = mockProducts.filter(p => p.publisher.userId === 'current_user');
    const result = filterAndSortProducts(myProducts, params);
    
    setTimeout(() => {
      res.status(200).json(result);
    }, 200);
  },
  
  // 收藏商品
  'POST /api/products/favorite/:productId': (req, res) => {
    const { productId } = req.params;
    
    setTimeout(() => {
      res.status(200).json({
        success: true,
        message: '收藏成功'
      });
    }, 200);
  },
  
  // 取消收藏
  'DELETE /api/products/favorite/:productId': (req, res) => {
    const { productId } = req.params;
    
    setTimeout(() => {
      res.status(200).json({
        success: true,
        message: '取消收藏成功'
      });
    }, 200);
  },
  
  // 获取我的收藏
  'GET /api/products/favorites/my': (req, res) => {
    const { page = 1, pageSize = 10 } = req.query;
    const favoriteProducts = mockProducts.slice(0, 8); // 模拟收藏的商品
    
    const startIndex = (Number(page) - 1) * Number(pageSize);
    const endIndex = startIndex + Number(pageSize);
    const paginatedFavorites = favoriteProducts.slice(startIndex, endIndex);
    
    const favorites = paginatedFavorites.map((product, index) => ({
      id: `favorite_${index}`,
      productId: product.id,
      userId: 'current_user',
      favoritedAt: new Date(Date.now() - index * 24 * 60 * 60 * 1000),
      product
    }));
    
    setTimeout(() => {
      res.status(200).json({
        favorites,
        total: favoriteProducts.length
      });
    }, 250);
  }
});